package justbuy.payment.service.alipay;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.ironrhino.core.util.CodecUtils;
import org.ironrhino.core.util.HttpClientUtils;

class AlipayHelper {

	static final String ENCODING = "UTF-8";

	static final String GATEWAY = "https://www.alipay.com/cooperate/gateway.do";

	public static boolean verifySign(Map<String, String> params, String key) {
		return sign(params, key).equals(params.get("sign"));
	}

	public static void addSign(Map<String, String> params, String key) {
		String sign = sign(params, key);
		params.put("sign_type", "MD5");
		params.put("sign", sign);
	}

	private static String sign(Map<String, String> params, String key) {
		if (params == null || params.size() == 0)
			return null;
		String str = toQueryString(params, true);
		return CodecUtils.md5Hex(str + key,ENCODING);
	}

	public static String toQueryString(Map<String, String> params,
			boolean excludeSign) {
		List<String> keys = new ArrayList<String>(params.keySet());
		Collections.sort(keys);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < keys.size(); i++) {
			String key = keys.get(i);
			String value = params.get(key);
			if (excludeSign && (key.equals("sign") || key.equals("sign_type")))
				continue;
			if (StringUtils.isBlank(value)) {
				params.remove(key);
				continue;
			}
			sb.append(key).append("=").append(value).append("&");
		}
		sb.deleteCharAt(sb.length() - 1);
		return sb.toString();
	}

	public static Map<String, String> getVerifiedParams(
			Map<String, String> params, String partner, String key) {
		String notify_id = params.get("notify_id");
		if (!verifyNotify(notify_id, partner))
			return null;
		return verifySign(params, key) ? params : null;
	}

	private static boolean verifyNotify(String partner, String notify_id) {
		StringBuilder sb = new StringBuilder();
		sb.append(GATEWAY).append("?service=notify_verify");
		sb.append("&partner=").append(partner).append("&notify_id=")
				.append(notify_id);
		String url = sb.toString();
		String responseText = HttpClientUtils.getResponseText(url);
		return "true".equals(responseText);
	}

}
